import socketserver
import json
import struct


def login(dic,):
    with open('userinfo.txt', 'r') as f:
        for line in f:
            username, password = line.strip().split('|')
            if dic['username'] == username and password == dic['password']:
                flag = 1
                break
        else:
            flag = 0
    dic = {'operate':'login', 'flag':flag}
    return dic


def upload(dic):
    pass


class Myserver(socketserver.BaseRequestHandler):
    def mysend(self, dic):
        str_dic = json.dumps(dic)
        bdic = str_dic.encode('utf-8')
        len_dic = len(bdic)
        msg_len = struct.pack('i', len_dic)
        self.request.send(msg_len)
        self.request.send(bdic)

    def myrecv(self):
        pass

    def handle(self):
        msg_len = self.request.recv(4)
        msg_len = struct.unpack('i', msg_len)[0]
        str_dic = self.request.recv(msg_len).decode('utf-8')
        dic = json.loads(str_dic)

        if dic['operate'] == 'login':
            ret = login(dic)
            self.mysend(ret)

        elif dic['operate'] == 'upload':
            upload(dic)



server = socketserver.ThreadingTCPServer(('127.0.0.1', 9000), Myserver)
server.serve_forever()